<template>
    <div class="email-details">
        <div class="head-title">
            <span class="" @click="linkTo">{{listData.subject}}</span>
            <span @click="goTo">跳转至相应模块 &gt;</span>
        </div>

        <section>
            <div class="user-info">
                <div>
                    <img :src="getAvatar(listData.avatar_path)" />
                    <div>
                        <span>{{listData.user_name}}</span>
                        <div>
                            <template v-if="Object.keys(listData).length != 0">
                                <span v-if="listData.role_name.length > 0">{{listData.role_name[0]}}</span>
                                <span v-if="listData.org_name.length > 0">{{listData.org_name[0]}}</span>
                            </template>
                        </div>
                    </div>
                </div>
                <div>
                    <div>
                        <span>主题：</span><span>{{listData.subject}}</span>
                    </div>
                    <div>
                        <span>发件人：</span><span>{{listData.user_name}}</span>
                    </div>
                    <div>
                        <span>收件人：</span><span>{{getUserName(listData.user, 1)}}</span>
                    </div>
                    <div>
                        <span>抄送人：</span><span>{{getUserName(listData.user, 3)}}</span>
                    </div>
                    <div>
                        <span>时间：</span><span>{{listData.create_time}}</span>
                    </div>
                    <div class="attachment">
                        <span>附件：</span>
                        <div>
                            <template v-if="Object.keys(listData).length != 0 && listData.file.length > 0">
                                <span v-for="(item, index) in listData.file" :key="index">
                                    <img alt="附件" src="./../../../assets/email/images/attachment.png" />
                                    <span class="name" @click="previewFile(item)">{{item.name + '.' + item.postfix}}</span>
                                    <a :data-link="`${BASE_URL}/api/email/file?company=BL&device_name=TE-0600R&sign=b0BrQILFn4dP8u00r54qTIlpLXBdNMWi&actioncode=get_file&data[id]=${queryInfo.id}&data[fid]=${item.id}&data[token]=${item.token}`" @click="downSource">下载</a>
                                    <!-- <a target="_blank" :href="`${BASE_URL}/api/email/file?company=BL&device_name=TE-0600R&sign=b0BrQILFn4dP8u00r54qTIlpLXBdNMWi&actioncode=get_file&data[id]=${queryInfo.id}&data[fid]=${item.id}&data[token]=${item.token}`">下载</a> -->
                                </span>
                            </template>
                            <span v-else style="color: #020202;font-size: 12px;">无</span>
                        </div>
                    </div>
                </div>
            </div>

            <div class="main-content" v-html="listData.content"></div>
        </section>

        <transition name="el-fade-in-linear">
			<div class="video-preview" :class="{activeLive: isActive}">
				<div class="maskingBox"
					v-loading="viewLoading.status"
					:element-loading-text="viewLoading.txt">
					<div class="masking_h">
						<span>视频预览</span>
						<i class="el-icon-close" @click="closeVideoView"></i>
					</div>
					<div class="masking_c">
						<nativeVideo v-if="showVideoPlayer" :playParam.sync="playParam"></nativeVideo>
					</div>
				</div>
			</div>
		</transition>

        <transition name="el-fade-in-linear" lock-scroll="false">
			<div class="document-preview" :class="{activeLive: isPDFActive}">
				<div class="maskingBox">
					<div class="masking_h">
						<span>文档预览</span>
						<i class="el-icon-close" @click="closePdfView"></i>
					</div>

					<div class="masking_c">
                    <div>
                        <div class="pdf-view">
                            <div 
                                v-if="viwPdfParam.loadedRatio > 0 && viwPdfParam.loadedRatio < 1" 
                                style="background-color: green; color: white; text-align: center" 
                                :style="{ width: viwPdfParam.loadedRatio * 100 + '%' }">
                                {{ Math.floor(viwPdfParam.loadedRatio * 100) }}%
                            </div>
                            <pdf ref="pdf" 
                                :src="viwPdfParam.src" 
                                :page="viwPdfParam.page"   
                                @progress="viwPdfParam.loadedRatio = $event" 
                                @error="pdfError" 
                                @num-pages="viwPdfParam.numPages = $event" 
                                @link-clicked="viwPdfParam.page = $event">
                            </pdf>
                        </div>

                        <el-pagination
                            @current-change="pdfPageChange"
                            :current-page="viwPdfParam.page"
                            :page-size="1"
                            layout="total,  prev, pager, next, jumper"
                            :total="viwPdfParam.numPages">
                        </el-pagination>
                    </div>
				</div>
				</div>
			</div>
		</transition>

        <el-dialog
            title="图片预览"
            class="picture-preview"
            :visible.sync="imgVisible"
            :close-on-click-modal="false">
            <div>
                <img :src="imgViewUrl">
            </div>
        </el-dialog>

        <el-dialog
			title="音频预览"
            class="audio-preview"
			:visible.sync="voiceVisible"
            :before-close="closeAudio"
			:close-on-click-modal="false">
			<div>
				<audio id="voicepoauy" controls="controls" :src="voiceViewUrl" controlsList="nodownload">
				    Your browser does not support the audio tag.
				</audio>
			</div>
		</el-dialog>
    </div>
</template>

<script>
    import pdf from 'vue-pdf';
    import nativeVideo from './../../common/nativeVideo';
    import defaultImg from './../../../assets/images/email/user.png';
    
    export default {
        data() {
            return {
                isActive: true,
                isPDFActive: true,
                imgVisible: false,
                voiceVisible: false,
                showVideoPlayer: false,
                queryInfo: null, // 邮件模块 、id
                voiceViewUrl: '',
                imgViewUrl: '',
                listData: {},
                playParam: {play_url: ''},
                viewLoading:{
                    status: false,
                    txt: '加载数据...'
                },
                viwPdfParam: {
                    src: '',
                    loadedRatio: 0,
                    page: 1,
                    numPages: 0,
                    rotate: 0
                },
            }
        },
        created() {
            this.queryInfo = {
                id: +this.$route.query.id,
                flag: +this.$route.query.flag
            }
            this.getList();
        },
        components: {
            pdf,
            nativeVideo
        },
        methods: {
            /**
             * 本页下载
             */
            downSource(ev) {
                window.location.href = ev.currentTarget.dataset.link;
            },
            /**
             * 获取用户头像
             * @param {Object} obj 用户信息
             */
            getAvatar(obj) {
                if (obj) {
                    return this.BASE_URL + obj;
                } else {
                    return defaultImg;
                }
            },
            /**
             * 获取收件人名称
             * @param {Object} obj 收件人列表
             * @param {Number} type 1-发件人 | 2-抄送人 | 3-外部收件人
             */
            getUserName(obj, type) {
                if (is_empty(obj)) {
                    return '';
                } else {
                    let text = '';

                    obj.filter(item => item.receive_type == type).forEach((item, index) => {
                        text += (index != 0 ? '，' : '') + item.name;
                    })

                    if (text === '') {
                        text = '无';
                    }

                    return text;
                }
            },
            /**
             * 路由跳转
             * @param {String} name 具体页面
             */
            linkTo(name) {
                this.$router.go(-1);
            },
            /**
             * 跳到对应的邮件模块
             * 邮箱标志（1：收件箱，2：草稿箱，3：已发送，4：废纸篓）
             */
            goTo() {
                let name = 'inbox';

                switch(this.queryInfo.flag) {
                    case 2:
                        name = 'drafts';
                        break;
                    case 3:
                        name = 'sent';
                        break;
                    case 4:
                        name = 'trash';
                        break;
                }

                let mailListId = JSON.parse(sessionStorage.getItem('mailListId'));

                if (mailListId) {
                    sessionStorage.setItem('mailListId', JSON.stringify({...mailListId, ...{[name]: this.queryInfo.id}}));
                } else {
                    sessionStorage.setItem('mailListId', JSON.stringify({[name]: this.queryInfo.id}));
                }
                
                this.$router.push(`/email/${name}`);
            },
            /**
             * 获取邮件详细信息
             */
            getList() {
                let success = (res => {
                    this.listData = res.data;
                    this.changeStates();
                    let self = this;

                    this.$nextTick(() => {
                        let source = document.querySelectorAll('.download-source');
                        let previewS = document.querySelectorAll('.click-span-preview');
                        
                        source.forEach(item => {
                            item.addEventListener('click', function(ev) {
                                window.location.href = ev.currentTarget.dataset.link;
                            }, false)
                        })
                        previewS.forEach(item => {
                            item.addEventListener('click', function(ev) {
                                self.previewFile({id: +ev.currentTarget.dataset.id, file_type: +ev.currentTarget.dataset.type});
                            }, false)
                        })
                    })
                });

                this.$ajax({
                    url: "api/email/single",
                    method: "get",
                    params: {id: this.queryInfo.id},
                    func: {success: success}
                });
            },
            /**
             * 改变邮件状态 -- 未读改为已读
             */
            changeStates() {
                let flag = false;

                this.listData.user.forEach(item => {
                    if (item.receiver == this.$g.user_id && item.is_read == 0) {
                        flag = true;
                    }
                })
                let success = (res => {});

                if (flag) {
                    this.$ajax({
                        url: "api/email/user",
                        method: "put",
                        data: {id: this.queryInfo.id},
                        func: {success: success}
                    });
                }
            },
            /**
             * 预览附件
             * @param {Object} obj 附件信息
             * 文件类型（1：文档；2：日志；3：图片；4：压缩文件；5：音频文件；6：视频；7：应用程序；8：其他）
             */
            previewFile(obj) {
                this.viewLoading.status = true;

                switch(parseInt(obj.file_type)) {
                    case 1:
                        this.isPDFActive = false;
                        break;
                    case 3:
                        this.imgVisible  = true;
                        break;
                    case 5:
                        this.voiceVisible = true;
                        break;
                    case 6:
                        this.isActive = false;
                        break;
                    default: 
                        this.$message.warning("不支持预览的资源类型");
                        return false;
                }

                let success = ( res => {
                    let result  = res.data;

                    switch(parseInt(obj.file_type)) {
                        case 1:
                            this.pdfView( result.path);
                            break;
                        case 3:
                            this.imgView(result.path);
                            break;
                        case 5:
                            this.voiceView(result.path);
                            break;
                        case 6:
                            this.videoView(result.path);
                            break;
                        default: 
                            this.$message.warning("不支持预览的资源类型");
                    }
                })
                let fail = (res => {
                    this.viewLoading.status = false;
                    this.$message.error(res.msg);
                })
                
                this.$ajax({
                    url: "api/resource/view_info",
                    method: "get",
                    params: {
                        id: obj.id, 
                        is_email_file: 1
                    },
                    func: {
                        success: success,
                        fail: fail
                    }
                });
            },
            /**
             * 关闭音频播放
             */
            closeAudio() {
                this.voiceVisible = false;
                document.getElementById("voicepoauy").pause();
            },
            /**
             * 音频预览
             */
            voiceView(url) {
                this.voiceViewUrl = url;
                document.getElementById("voicepoauy").load();	
            },
            /**
             * 图片预览
             */
            imgView(url) {
                this.imgViewUrl = url;
            },
            /**
             * 文档预览
             */
            pdfView(url) {
                this.viwPdfParam.src = pdf.createLoadingTask(url);
            },
            /**
             * 改变文档页数
             */
            pdfPageChange(val) {
                this.viwPdfParam.page  = val;
            },
            /**
             * 文档预览失败
             */
            pdfError: function(err) {
                this.$message.error('读取文件失败');
            },
            /**
             * 关闭文档预览
             */
            closePdfView() {
                this.isPDFActive = true;
            },
            /**
             * 关闭视频预览
             */
            closeVideoView() {
                this.showVideoPlayer = false;
                this.isActive = true;
            },
            /**
             * 视频预览
             */
            videoView(url) {
                this.showVideoPlayer = true;
                this.playParam.play_url = url;
            },
        },
    }
</script>

<style lang="scss">
    .email-details {
        position: relative;
        margin: 30px auto;
        width: 1000px;
        height: calc(100% - 60px);
        background: #fff;
        overflow: hidden;

        .head-title {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding-left: 60px;
            height: 60px;
            border-bottom: 1px solid #eee;

            >span:first-child {
                font-size: 18px;
                cursor: pointer;
            }

            >span:first-child:before {
                display: inline-block;
                content: "";
                position: absolute;
                top: 25px;
                left: 30px;
                width: 9px;
                height: 9px;
                border-width: 0 0 2px 2px;
                border-color: #888;
                border-style: solid;
                transform: rotateZ(45deg);
            }

            >span:last-child {
                padding-right: 25px;
                font-size: 14px;
                color: #6178A5;
                cursor: pointer;
            }
        }

        section {
            height: calc(100% - 60px);
            overflow: auto;
            box-sizing: border-box;
            
            .user-info {
                padding: 20px 60px 15px;
                line-height: 23px;
                background: #F9F9F9;

                >div:first-child {
                    display: flex;
                    justify-content: flex-start;
                    align-items: center;
                    padding-bottom: 20px;
                    border-bottom: 1px dashed #EAEAEA;

                    img {
                        margin-right: 20px;
                        width: 40px;
                        height: 40px;
                        // object-fit: contain;
                        border-radius: 50%;
                    }

                    >div {
                        flex: 1;
                    
                        >span:first-child {
                            font-size: 14px;
                            color: #333333;
                        }
                    }

                    >div>div span {
                        display: inline-block;
                        margin-right: 8px;
                        padding: 3px 15px;
                        font-size: 12px;
                        color: #888888;
                        line-height: 1.3;
                        background: #EAEAEA;
                        border-radius: 10.5px;
                    }
                }

                >div:last-child {
                    padding-top: 10px;
                    font-size: 12px;

                    >div {
                        display: flex;

                        >span:first-child {
                            padding-right: 10px;
                            width: 60px;
                            text-align: right;
                            box-sizing: border-box;
                        }

                        >span:last-child {
                            flex: 1;
                        }
                    }

                    .attachment {
                        display: flex;

                        >span {
                            width: 60px;
                        }

                        >div {
                            display: flex;
                            flex-wrap: wrap;
                            flex: 1;

                            >span {
                                display: flex;
                                justify-content: flex-start;
                                align-items: center;
                                margin-right: 30px;
                                font-size: 14px;
                                color: #586F8B;

                                img {
                                    margin-right: 5px;
                                }

                                a {
                                    margin-left: 15px;
                                    padding: 0 18px;
                                    color: #fff;
                                    font-size: 12px;
                                    background: #8199C7;
                                    border-radius: 4px;
                                    text-decoration: none;
                                    cursor: pointer;
                                }

                                span {
                                    cursor: pointer;
                                }
                            }
                        }
                    }
                }
            }

            .main-content {
                padding: 40px 60px;
                font-size: 14px;
                color: #333333;
                line-height: normal;
            }
        }

        .activeLive{
			opacity: 0;
			visibility: hidden;
		}

        .el-dialog__wrapper{
			.el-dialog__body {
                text-align: center;
				padding: 0;
            }
		}

        .masking_h {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 10px;
            height: 40px;
            background: #348EFC;

            >span,
            >i {
                font-size: 16px;
                color: #fff;
            }

            >i{
                cursor: pointer;
            }
        }

        .video-preview {
            display: flex;
            justify-content: center;
            align-items: center;
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			transition: .5s;
			background: rgba(0, 0, 0, 0.5);
			z-index: 3;

            .maskingBox {
                width: 70vw;
                height: 70vh;
                max-width: 1000px;
                max-height: 600px;
				background: #fff;
			}

            .masking_c {
                height: calc(100% - 40px);
                box-sizing: border-box;

                >div >div {
                    height: 600px;
                }
            }
        }

        .document-preview {
			display: flex;
            justify-content: center;
            align-items: center;
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			transition: .5s;
			background: rgba(0, 0, 0, 0.5);
			z-index: 3;

			.maskingBox {
                width: 70vw;
                height: 70vh;
                max-width: 1200px;
                max-height: 900px;
				background: #fff;
			}

            .masking_c {
                height: calc(100% - 40px);
                box-sizing: border-box;

                >div {
                    height: 100%;

                    .pdf-view{
                        height: calc(100% - 70px);
                        overflow: hidden;
                        overflow-y: auto;

                        >span {
                            width: 100%;
                        }
                    }

                    .el-pagination {
                        padding: 20px 0;
                        text-align: center;
                        height: 70px;
                        box-sizing: border-box;
                    }
                }
            }
        }

		.picture-preview {
			display: flex;
            align-items: center;
            justify-content: center;
			margin: 0;

            .el-dialog {
                margin: 0;
                margin-top: 0 !important;
                width: 70vw;
                height: 70vh;
                max-width: 1200px;
                max-height: 900px;
                overflow: hidden;

                .el-dialog__body {
                    padding: 20px 0;
                    width: 100%;
                    height: calc(100% - 40px);
                    box-sizing: border-box;

                    div {
                        padding: 20px 40px 40px;
                        width: 100%;
                        height: 100%;
                        overflow-y: auto;
                        box-sizing: border-box;

                        img {
                            width: 100%;
                        }
                    }
                }
            }
        }

        .audio-preview {
            display: flex;
            align-items: center;
            justify-content: center;
			margin: 0;

            .el-dialog {
                margin: 0;
                margin-top: 0 !important;
                width: 500px;
                height: 300px;

                .el-dialog__body {
                    padding: 20px 0;
                    width: 100%;
                    height: calc(100% - 40px);
                    box-sizing: border-box;

                    div {
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        padding: 0 40px;
                        width: 100%;
                        height: 100%;
                        box-sizing: border-box;
                    }
                }
            }
        }
    }
</style>